#version 430

uniform sampler2D u_heightmap;
uniform float u_scale;
uniform float u_offset;
uniform vec3 u_gnd2sun;//this is normalized

uniform float u_duv;
uniform float u_dxz;


in vec4 vcolor;
in vec2 vuv;

out vec4 fragColor;

void main()
{
    vec2 tc_up = vec2(vuv.x, vuv.y - u_duv );
    vec2 tc_bottom = vec2(vuv.x, vuv.y + u_duv);
    vec2 tc_left = vec2(vuv.x - u_duv, vuv.y);
    vec2 tc_right = vec2(vuv.x + u_duv, vuv.y);

    float hup = (texture(u_heightmap, tc_up).r + u_offset) * u_scale;
    float hdown = (texture(u_heightmap, tc_bottom).r + u_offset) * u_scale;
    float hleft = (texture(u_heightmap, tc_left).r + u_offset) * u_scale;
    float hright = (texture(u_heightmap, tc_right).r + u_offset) * u_scale;

    float delta = u_dxz * 2.0;
    vec3 n = normalize(vec3((hup - hdown) / delta, 1.0 , (hleft - hright) / delta));
    float diffuseCoeff = dot(n, u_gnd2sun);

    fragColor = vec4(vcolor.xyz * diffuseCoeff, 1.0);
}